<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;

abstract class Controller
{

    protected const SUCCESS_CODE = '00000';
    protected const ERROR_CODE   = 'B0001';

    /**
     * 定义模型
     *
     * @var mixed
     */
    protected $model;

    /**
     * 构造器
     */
    public function __construct()
    {
        $this->initialize();
    }

    /**
     * 初始化方法，子类重写以设置模型
     *
     * @return void
     */
    protected function initialize(): void {}

    /**
     * 自定义成功响应方法
     *
     * @param string $msg
     * @param mixed  $data
     * @param bool   $forceObject 当为 true 时强制将数组转换为 object
     * @return Response
     */
    protected function success(string $msg = '一切ok', ?array $data = null, ?bool $forceObject = false): Response
    {
        $result = [
            'code' => self::SUCCESS_CODE,
            'msg'  => $msg,
            'data' => $forceObject ? (object)$data : $data,
        ];

        return response($result);
    }

    /**
     * 自定义成功响应（带列表）
     *
     * @param string $message
     * @param array  $list
     * @param int    $total
     * @return Response
     */
    protected function successList(string $msg = '一切ok', array $list = [], int $total = 0): Response
    {
        $result = [
            'code' => self::SUCCESS_CODE,
            'msg'  => $msg,
            'data' => [
                'list'  => $list,
                'total' => $total,
            ],
        ];
        return response($result);
    }

    /**
     * 自定义失败响应，默认 422 (Unprocessable Entity)
     *
     * @param int    $status
     * @param string $message
     * @param mixed  $data
     * @return Response
     */
    protected function error(int $status = 422, string $msg = '操作失败', $data = []): Response
    {
        $result = [
            'code' => self::ERROR_CODE,
            'msg'  => $msg,
            'data' => (object)$data,
        ];
        return response($result, $status);
    }
}
